# -*- coding: utf-8 -*-
# Project : flacon
# File : configureDialog.py
# (c) Alexander Sokolov sokoloff.a@gmail.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.



from settings import *
import encoder
import encoderConfigPage

from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *

import pyqticonloader


from configureDialog_ui import *
from flaconglobal import *

class ProgramEdit(QLineEdit):
   #****************************************************************
   #
   #****************************************************************
    def __init__(self, program, parent):
        QLineEdit.__init__(self, parent)
        self._programName = program
        encoderConfigPage.EncoderConfigPage.loadLineEdit("Programs/"+program, self)


   #****************************************************************
   #
   #****************************************************************
    def programName(self):
        return self._programName


   #****************************************************************
   #
   #****************************************************************
    def find(self):
        if self.text().isEmpty():
            self.setText(settings.findProgram(self._programName))


   #****************************************************************
   #
   #****************************************************************
    def write(self):
        encoderConfigPage.EncoderConfigPage.writeLineEdit("Programs/" + self._programName, self)



class ProgramButton(QToolButton):
   #****************************************************************
   #
   #****************************************************************
    def __init__(self, edit, parent):
        QToolButton.__init__(self, parent)
        self._edit = edit
        self.setIcon(pyqticonloader.icon(['document-open-folder', 'document-open', 'folder_open']))
        self.connect(self, SIGNAL('clicked()'), self.openProgFile)


   #****************************************************************
   #
   #****************************************************************
    def openProgFile(self):
        program = self._edit.programName()
        flt = self.tr("%1 program").arg(program)  + QString(" (%1);;").arg(program) + \
              self.tr("All files")              + " (*.*)"

        fileName = QFileDialog.getOpenFileName(self, self.tr("Select program file"), "/usr/bin/", flt)
        if (fileName):
            self._edit.setText(fileName)




class ConfigureDialog(QtGui.QDialog):
    _dialog = None

   #****************************************************************
   #
   #****************************************************************
    @classmethod
    def createAndShow(cls, parent, formatId = ""):
        if not ConfigureDialog._dialog:
            ConfigureDialog._dialog = ConfigureDialog(parent)

        ConfigureDialog._dialog.show(formatId)
        ConfigureDialog._dialog.raise_()
        ConfigureDialog._dialog.activateWindow()


   #****************************************************************
   #
   #****************************************************************
    def show(self, formatId = ""):
        page = self.form.pages.findChild(QWidget, formatId)
        pageIndex = self.form.pages.indexOf(page)

        if pageIndex<0:
            pageIndex = self.form.pages.currentIndex()

        self.form.pagesList.setCurrentRow(pageIndex)
        QDialog.show(self)


   #****************************************************************
   #
   #****************************************************************
    def closeConfigureDialog(self):
        ConfigureDialog._configureDialog = None


   #****************************************************************
   #
   #****************************************************************
    def __init__(self, parent=None):
        QtGui.QDialog.__init__(self, parent)

        self.form = Ui_configureDialog()
        self.form.setupUi(self)

        (width, ok)  = settings.value("ConfigureDialog/Width",  QVariant(self.size().width())).toInt()
        (height, ok) = settings.value("ConfigureDialog/Height", QVariant(self.size().height())).toInt()
        self.resize(width, height)

        #***********************************************************
        self.form.generalPage.setWindowTitle(self.tr("General configuration"))
        self.form.programsPage.setWindowTitle(self.tr("Full path of the external applications"))

        self.connect(self.form.pages, SIGNAL('currentChanged(int)'), self.setPage)

        self.pagesListInit()
        self.programsInit()
        self.form.pages.setCurrentIndex(0)

        #***********************************************************
        self.form.preGapComboBox.addItem(self.tr("Extract to separate file"), PregapFileTypes.ExtractToFile)
        self.form.preGapComboBox.addItem(self.tr("Add to first track"),       PregapFileTypes.AddToFirstTrack)


        encoderConfigPage.EncoderConfigPage.loadSpinBox('Encoder/ThreadCount', self.form.threadsCountSpin)
        encoderConfigPage.EncoderConfigPage.loadLineEdit('Encoder/TmpDir', self.form.tmpDirEdit)
        encoderConfigPage.EncoderConfigPage.loadComboBox('Tags/DefaultCodepage', self.form.codePageComboBox)
        encoderConfigPage.EncoderConfigPage.loadCheckBox('PerTrackCue/Create', self.form.perTrackCueCheck)
        encoderConfigPage.EncoderConfigPage.loadComboBox('PerTrackCue/Pregap', self.form.preGapComboBox)


        self.connect(self.form.tmpDirButton, SIGNAL('clicked()'), self.tmpDirShowDialog)
        self.form.tmpDirButton.setIcon(pyqticonloader.icon(['document-open-folder', 'document-open', 'folder_open']))

        self.connect(self.form.perTrackCueCheck, SIGNAL('clicked(bool)'), self._perTrackCueCheckClicked)
        self._perTrackCueCheckClicked(self.form.perTrackCueCheck.isChecked())


   #****************************************************************
   #
   #****************************************************************
    def done(self, res):
        settings.setValue("ConfigureDialog/Width",     QVariant(self.size().width()))
        settings.setValue("ConfigureDialog/Height",    QVariant(self.size().height()))
        encoderConfigPage.EncoderConfigPage.writeComboBox('Tags/DefaultCodepage',  self.form.codePageComboBox)

        if res:
            encoderConfigPage.EncoderConfigPage.writeSpinBox('Encoder/ThreadCount', self.form.threadsCountSpin)
            encoderConfigPage.EncoderConfigPage.writeLineEdit('Encoder/TmpDir', self.form.tmpDirEdit)
            encoderConfigPage.EncoderConfigPage.writeCheckBox('PerTrackCue/Create', self.form.perTrackCueCheck)
            encoderConfigPage.EncoderConfigPage.writeComboBox('PerTrackCue/Pregap', self.form.preGapComboBox)

            for page in self.form.pages.findChildren(encoderConfigPage.EncoderConfigPage):
                page.write()

            for progEdit in self.form.pages.findChildren(ProgramEdit):
                progEdit.write()

        QDialog.done(self, res)
        self.setParent(None)
        ConfigureDialog._dialog = None


   #****************************************************************
   #
   #****************************************************************
    def setPage(self, pageIndex):
        self.form.pageTitle.setText(self.form.pages.currentWidget().windowTitle())
        self.form.pagesList.setCurrentRow(pageIndex)


   #****************************************************************
   #
   #****************************************************************
    def pagesListInit(self):
        pl = self.form.pagesList

        item = QListWidgetItem(self.form.pagesList)
        item.setText(self.tr("General"))
        item.setIcon(pyqticonloader.icon(['go-home', 'gohome']))
        pl.addItem(item)

        n=1
        for id in sorted(outputAudioFormats.keys()):
            fmt = outputAudioFormats[id]
            if fmt.configPageClass:
                page = fmt.configPageClass(self)
                page.setObjectName(fmt.id)
                self.form.pages.insertWidget(n, page)
                n += 1
                item = QListWidgetItem(self.form.pagesList)
                item.setText(fmt.name)
                item.setIcon(pyqticonloader.icon(['audio-x-generic', 'sound']))
                pl.addItem(item)


        item = QListWidgetItem(self.form.pagesList)
        item.setText(self.tr("Programs"))
        item.setIcon(pyqticonloader.icon(['applications-system', 'gear']))
        pl.addItem(item)

        # Set item width ........................
        width = 0
        for i in xrange(0, pl.count()):
            item = pl.item(i)
            width = max(width, pl.fontMetrics().width(item.text()))

        width = width + 42

        for i in xrange(0, pl.count()):
            item = pl.item(i)
            h =  pl.iconSize().height() + pl.fontMetrics().height() + 8
            item.setSizeHint(QSize(width, h))


        pl.setMaximumWidth(width + 2 * pl.frameWidth())


   #****************************************************************
   #
   #****************************************************************
    def programsInit(self):

        row=0
        for program in sorted(settings.programs()):
            edit = ProgramEdit(program, self.form.programsPage)

            label = QLabel(self.form.programsPage)
            label.setText(QString(program + ':'))
            label.setBuddy(edit)

            btn = ProgramButton(edit, self.form.programsPage)
            self.form.progsLayout.addWidget(label, row, 0)
            self.form.progsLayout.addWidget(edit,  row, 1)
            self.form.progsLayout.addWidget(btn,   row, 2)

            self.connect(self.form.progScanButton, SIGNAL('clicked()'), edit.find)
            row+=1


   #****************************************************************
   #
   #****************************************************************
    def tmpDirShowDialog(self):
        tmpDir = QFileDialog.getExistingDirectory(self, self.tr("Select temporary directory"), self.form.tmpDirEdit.text())
        if (tmpDir):
            self.form.tmpDirEdit.setText(tmpDir)


   #****************************************************************
   #
   #****************************************************************
    def _perTrackCueCheckClicked(self, checked):
        self.form.preGapComboBox.setEnabled(checked)
